<template>
  <div>
    <!-- <a-button type="primary" @click="showModal">Open Modal</a-button> -->
    <a-modal
      ref="modalRef"
      :width="600"
      :wrap-style="{ overflow: 'hidden' }"
      v-model:visible="props.visible"
      @ok="handleOk"
      @update:visible="updateVisible"
      @close="updateVisible(false)"
    >
      <a-form ref="userFormRef" :model="props.docData" :labelCol="{ span: 24 }" :wrapperCol="{ span: 24 }">
        <div v-if="!isUpdate">
          <a-form-item label="标题" name="title" :rules="[{ required: true, message: '请输入标题' }]">
            <a-input v-model:value="props.docData.title" placeholder="请输入标题"></a-input>
            <!-- <span>{{ props.docData.title }}</span> -->
          </a-form-item>
          <a-form-item v-if="createBy === 'text'" label="内容" name="content" :rules="[{ required: true, message: '请输入内容' }]">
            <a-textarea v-model:value="props.docData.content" placeholder="请输入内容"></a-textarea>
            <!-- <div id="vditor">{{vditor}}</div> -->
          </a-form-item>
          <a-form-item v-if="createBy === 'upload'" name="file" label="文件" :rules="[{ required: true, message: '请上传文件' }]">
            <!-- <a-button>
              <template #icon><upload-outlined style="font-size: 14px" /></template>
              <span style="font-size: 14px">上传文档</span>
            </a-button> -->

            <a-upload
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              :multiple="true"
              :file-list="fileList"
              @change="handleChange"
              >
              <a-button>
                <upload-outlined style="font-size: 14px" />
                <span style="font-size: 14px">上传文档</span>
              </a-button>
            </a-upload>
          </a-form-item>
        </div>

        <div v-if="isUpdate">
          <a-form-item label="标题" name="title" :rules="[{ required: true, message: '请输入标题' }]">
            <a-input v-model:value="props.docData.title" placeholder="请输入标题"></a-input>
            <!-- <span>{{ props.docData.title }}</span> -->
          </a-form-item>
          <a-form-item v-if="createBy === 'text'" name="content" label="内容" :rules="[{ required: true, message: '请输入内容' }]">
            <a-textarea v-model:value="props.docData.content" placeholder="请输入内容"></a-textarea>
            <!-- <div id="vditor">{{vditor}}</div> -->
          </a-form-item>
          <a-form-item v-if="createBy === 'upload'" name="file" label="文件" :rules="[{ required: true, message: '请上传文件' }]">
            <a-button>
              <template #icon><upload-outlined style="font-size: 14px" /></template>
              <span style="font-size: 14px">上传文档</span>
            </a-button>
          </a-form-item>
        </div>
      </a-form>

      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">{{ isUpdate ? '修改文档' : '新增文档' }}</div>
      </template>
      <template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts" setup name="AiragKnowledgeDocTextModal">
import { ref, computed, CSSProperties, watch, watchEffect, defineProps, defineEmits } from 'vue';
import { useDraggable } from '@vueuse/core';
import { KnowledgeApi } from '../api/KnowledgeApi';
import Vditor from 'vditor';
import { is } from '@/utils/is';
import { done } from 'nprogress';
import { UploadChangeParam, UploadProps } from 'ant-design-vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isUpdate: {
    type: Boolean,
    default: false
  },
  createBy: {
    type: String,
    default: ''
  },
  docData: {
    type: Object,
    default: {}
  }
});

// const form = ref({
//   content: '',
//   createBy: '',
//   createBy_dictText: '',
//   createTime: '',
//   id: '',
//   knowledgeId: props.knowledgeId,
//   metadata: '',
//   status: '',
//   sysOrgCode: '',
//   tenantId: null,
//   title: '',
//   type: '',
//   updateBy: '',
//   updateTime: '',
// })


const uploadUrl = ref<string>("192.168.18.39:8088/airag/knowledge/doc/import/zip");


const fileList = ref<UploadProps['fileList']>([
      {
        uid: '-1',
        name: 'xxx.txt',
        status: 'done',
        url: 'http://www.baidu.com/xxx.txt',
      },
    ]);

const emits = defineEmits(['update:visible', 'done']);

const userFormRef = ref<any>(null);

// const isUpdate = ref(false)

// const visible = ref<boolean>(false);
const modalTitleRef = ref<HTMLElement>(null);
// const showModal = () => {
//   visible.value = true;
// };
const { x, y, isDragging } = useDraggable(modalTitleRef);

const updateVisible = value => {
  emits('update:visible', value);
};
const handleOk = async (e: MouseEvent) => {
  // debugger;
  // console.log(userFormRef.value);
  if (userFormRef.value) {
    userFormRef.value
      .validate()
      .then(async () => {
        // console.log('submit', props.docData);
        if (props.isUpdate) {
          // console.log('update', props.docData.id);

          KnowledgeApi.knowledgeEditDoc({
            knowledgeId: props.docData.knowledgeId,
            id: props.docData.id,
            content: props.docData.content,
            title: props.docData.title,
            type: 'text'
          })
            .then(res => {
              // console.log('11111',res);
              updateVisible(false);
              // emits('done');
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log('create');
          KnowledgeApi.knowledgeEditDoc({
            knowledgeId: props.docData.knowledgeId,
            content: props.docData.content,
            title: props.docData.title,
            type: 'text'
          })
            .then(res => {
              // console.log('11111',res);
              updateVisible(false);
              // emits('done');
            })
            .catch(err => {
              console.log(err);
            });
        }
        emits('done')
        updateVisible(false);
      })
      .catch(err => {
        console.log(err);
      });
  }

  // console.log(props.docData);
  // debugger
  // emits('done')
  // updateVisible(false);
};

const vditor = new Vditor('vditor', {
  height: 500, // 编辑器高度
  mode: 'ir', // 编辑模式：ir（即时渲染）、sv（分屏）、wysiwyg（所见即所得）
  toolbar: [
    // 自定义工具栏
    'emoji',
    'headings',
    'bold',
    'italic',
    'link',
    '|',
    'list',
    'ordered-list',
    'check',
    'outdent',
    'indent',
    '|',
    'quote',
    'code',
    'inline-code',
    'insert-before',
    'insert-after',
    '|',
    'upload',
    'table',
    'math',
    'mermaid',
    'pagebreak',
    '|',
    'undo',
    'redo',
    '|',
    'fullscreen',
    'edit-mode'
  ],
  upload: {
    // 文件上传配置（可选）
    url: '/api/upload', // 上传接口地址
    filename: name => name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '') // 文件名处理
  }
});

const startX = ref<number>(0);
const startY = ref<number>(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });
watch([x, y], () => {
  if (!startedDrag.value) {
    startX.value = x.value;
    startY.value = y.value;
    const bodyRect = document.body.getBoundingClientRect();
    const titleRect = modalTitleRef.value.getBoundingClientRect();
    dragRect.value.right = bodyRect.width - titleRect.width;
    dragRect.value.bottom = bodyRect.height - titleRect.height;
    preTransformX.value = transformX.value;
    preTransformY.value = transformY.value;
  }
  startedDrag.value = true;
});
watch(isDragging, () => {
  if (!isDragging) {
    startedDrag.value = false;
  }
});
watchEffect(() => {
  if (startedDrag.value) {
    transformX.value = preTransformX.value + Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) - startX.value;
    transformY.value = preTransformY.value + Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) - startY.value;
  }
});
const transformStyle = computed<CSSProperties>(() => {
  return {
    transform: `translate(${transformX.value}px, ${transformY.value}px)`
  };
});
</script>
